//
//  DefaultKeyboardWordPad.swift
//  Keyboard
//
//  Created by 周张林 on 17/8/12.
//  Copyright © 2017年 周张林. All rights reserved.
//

import UIKit

/// 文字
class DefaultKeyboardWordPad:UIView
{
    static let wordArray = ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m","space"];
    
    static let WORDArray = ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M","space"];
    
    weak var inputController:UIInputViewController?
    weak var delegate:KeyboardDelegate?
    
    var btnArray:[DefaultKeyboardBtn]! = []
    
    var trasitionWordBtn:UIButton!
    var deleteBtn:UIButton!
    var numBtn:UIButton!
    var returnBtn:UIButton!
    var emojiBtn:UIButton!
    var tipView:WordTipView!
    
    let margin:CGFloat = 5
    var isTrans = false
    
    var lexicon:UILexicon?
    var currentString = ""
    
    override init(frame: CGRect) {

        super.init(frame: frame)
        backgroundColor = UIColor.clear
        
        DispatchQueue.global().async {
            WordsModel.instance.loadWords()
        }
        
        addControls()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addControls(){
        for i in  0...26 {
            let btn = DefaultKeyboardBtn.newButton(title: DefaultKeyboardWordPad.wordArray[i], tag: i, kbDelegate: self)
            btnArray.append(btn)
            addSubview(btn)
        }
        //单词提示
        tipView = WordTipView()
        tipView.delegate = self
        addSubview(tipView)
        
        // 大小写装换
        trasitionWordBtn = DefaultKeyboardBtn.newButton(title: "⇧", tag: 27, kbDelegate: self)
        addSubview(trasitionWordBtn)
        
        //delete
        deleteBtn = DefaultKeyboardBtn.newButton(title: "⌫", tag: 28, kbDelegate: self,fontSize:18)
        addSubview(deleteBtn)
        
        //数字键
        numBtn = DefaultKeyboardBtn.newButton(title: "123", tag: 29, kbDelegate: self,fontSize:18)
        addSubview(numBtn)
        
        //回车
        returnBtn = DefaultKeyboardBtn.newButton(title: "↵", tag: 30, kbDelegate: self,fontSize:32)
        addSubview(returnBtn)
        
        //表情
        emojiBtn = DefaultKeyboardBtn.newButton(title: "😄", tag: 31, kbDelegate: self)
        addSubview(emojiBtn)
    }
    
    override func layoutSubviews() -> Void {
        
        let ROW:CGFloat = 5
        
        let smallBtnW = (self.frame.size.width - 11*margin)/10;
        let btnH = (self.frame.size.height - 5*margin)/ROW;
        
        tipView.frame.size = CGSize(width:frame.size.width-50,height:btnH)
        tipView.scrollView.frame.size = tipView.frame.size
        
        for i in 0..<10 {
            let btn = self.btnArray[i];
            btn.frame = CGRect(x:margin + CGFloat(i)*(smallBtnW + margin), y:margin+btnH, width:smallBtnW, height:btnH)
        }
        
        let margin2 = (self.frame.size.width - 8*margin - 9*smallBtnW)/2;
        for i in 10..<19 {
            let btn = self.btnArray[i];
            btn.frame = CGRect(x:margin2 + CGFloat(i-10)*(smallBtnW + margin), y:2*margin + btnH*2, width:smallBtnW, height:btnH)
        }

        self.trasitionWordBtn.frame = CGRect(x:margin, y:3*margin + 3*btnH, width:smallBtnW*1.3, height:btnH)
        
        self.deleteBtn.frame = CGRect(x:frame.width-smallBtnW * 1.3-margin,y:3*margin + 3*btnH, width:smallBtnW * 1.3, height:btnH)
        
        for i in 19..<26 {
            let btn = self.btnArray[i]
            var temp = self.btnArray[i-8].frame
            temp.origin.y = 3*margin + 3*btnH
            btn.frame = temp
        }
        
        let bigBtnW = (self.frame.size.width - 5*margin)/4;
        self.numBtn.frame = CGRect(x:margin, y:4*margin + btnH*4, width:bigBtnW/2-margin, height:btnH);
        
        self.emojiBtn.frame = CGRect(x:bigBtnW/2 + margin, y:4*margin + btnH*4, width:bigBtnW/2-margin, height:btnH);
        
        let lastBtn = btnArray.last
        lastBtn?.frame = CGRect(x:margin+bigBtnW, y:4*margin + btnH*4, width:bigBtnW * 2 + margin*2, height:btnH);
        
        self.returnBtn.frame = CGRect(x:4*margin + 3*bigBtnW, y:4*margin + btnH*4, width:bigBtnW, height:btnH);
    }
    
    func trasitionWord() -> Void {
        for i in  0...26 {
            let btn = btnArray[i]
            if isTrans {
                btn.setTitle(DefaultKeyboardWordPad.WORDArray[i], for: .normal)
                trasitionWordBtn.alpha = 0.5
            }else{
                btn.setTitle(DefaultKeyboardWordPad.wordArray[i], for: .normal)
                trasitionWordBtn.alpha = 1
            }
        }
    }
    
    func showWordTip() -> Void {
        tipView.clear()
        if currentString.characters.count>0 {
            let words = WordsModel.instance.searchWords(pre: currentString )
            if words.count == 0 || words[0] != currentString {
                tipView.add(word: currentString)
            }
            for word in WordsModel.instance.searchWords(pre: currentString ){
                tipView.add(word: word)
            }
        }
    }
    
    func insertText(word:String!)->Void{
        inputController?.textDocumentProxy.insertText(word)
        currentString = ""
        tipView.clear()
        //自动首字母大写
        
        //自动添加一个空格
        inputController?.textDocumentProxy.insertText(" ")
        
        //联想
        if let words = WordsModel.instance.associate(pre: word) {
            for word in words {
                tipView.add(word: word)
            }
        }
    }
    
    deinit {
        inputController = nil
        btnArray = nil
        deleteBtn = nil
        trasitionWordBtn = nil
        numBtn = nil
        returnBtn = nil
        delegate = nil
    }
}

extension DefaultKeyboardWordPad:WordTipViewDelgate{
    func onSelectedWord(word:String!)->Void{
        
        if let lexicon = self.lexicon {
            for entity in lexicon.entries {
                if entity.userInput == word {
                    insertText(word:entity.documentText)
                    return
                }
            }
        }
        insertText(word:word)
    }
}

extension DefaultKeyboardWordPad:DefaultKeyboardBtnDelegate{
    func didClick(_ sender:DefaultKeyboardBtn)->Void{
        switch sender.tag
        {
        case 26:
            if currentString.characters.count>0 {
                insertText(word: currentString)
            }
            else
            {
                inputController?.textDocumentProxy.insertText(" ")
                currentString = ""
            }
        case 27:
            isTrans = !isTrans
            trasitionWord()
            break
        case 28:
            if currentString.characters.count>0{
                currentString.remove(at: currentString.index(before: currentString.endIndex))
            }else{
                inputController?.textDocumentProxy.deleteBackward()
            }
            showWordTip()
            break
        case 29:
            delegate?.showNumPad()
        case 30:
            inputController?.textDocumentProxy.insertText("\n")
        case 31:
            delegate?.showEmojiPad!()
        default:
            if self.isKind(of: DefaultKeyboardWordPad.classForCoder() ) {
                currentString.append((sender.titleLabel?.text)!)
                showWordTip()
            }else{
                inputController?.textDocumentProxy.insertText((sender.titleLabel?.text)!)
            }
        }
    }
}
